package com.future.mayi.activity;


import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.text.TextUtils;
import android.view.View;

import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.future.baselib.utils.SealConst;
import com.future.baselib.view.NoScrollViewPager;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.dialog.CommonDialog;
import com.future.mayi.fragment.RegisterCodeFragment;
import com.future.mayi.fragment.RegisterPhoneFragment;
import com.future.mayi.jpush.JPushManager;
import com.future.mayi.model.UserInfoModel;
import com.future.mayi.response.LoginResponse;
import com.future.mayi.utils.BroadcastManagerUtil;
import com.future.mayi.utils.SharedPreferencesUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class RegisterActivity extends BaseTitleActivity {


    @BindView(R.id.view_pager)
    NoScrollViewPager viewPager;

    private RegisterPhoneFragment phoneFragment;
    private RegisterCodeFragment codeFragment;
    private List<Fragment> fragmentList;

    private String openid, icon, name;
    private int type = 1;

    /**
     * @param type 1手机登录  2注册 3绑定
     */
    public static void startActivity(Context context, int type) {
        Intent intent = new Intent(context, RegisterActivity.class);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, String openid, String icon, String name) {
        Intent intent = new Intent(context, RegisterActivity.class);
        intent.putExtra("openid", openid);
        intent.putExtra("icon", icon);
        intent.putExtra("name", name);
        intent.putExtra("type", 3);
        context.startActivity(intent);
    }


    @Override
    protected void initTopBar() {
        initBack();
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_register);
        setViewLineVisibility(View.GONE);
    }

    @Override
    protected void initView() {
        if (getIntent() != null) {
            type = getIntent().getIntExtra("type", 1);
            openid = getIntent().getStringExtra("openid");
            icon = getIntent().getStringExtra("icon");
            name = getIntent().getStringExtra("name");
        }

        phoneFragment = new RegisterPhoneFragment();
        phoneFragment.setType(type);
        codeFragment = new RegisterCodeFragment();
        codeFragment.setType(type);
        fragmentList = new ArrayList<>(2);
        fragmentList.add(phoneFragment);
        fragmentList.add(codeFragment);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return super.getPageTitle(position);
            }
        });
    }

    @Override
    protected void initDates() {

    }

    @Override
    protected void initListener() {

    }


    public void checkPhoneIsRegister(final String phone, final String countryId, final String countryCode) {
        if (type != 3) return;
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode(ApiCst.isRegByMobile)
                .addParam("mobile", phone)
                .addParam("country_id", countryId)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse baseResponse) {
                        String is_reg = "";
                        String is_bind_wechat = "";
                        try {
                            JSONObject object = new JSONObject(baseResponse.content);
                            is_reg = object.optString("is_reg");
                            is_bind_wechat = object.optString("is_bind_wechat");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (TextUtils.equals(phoneFragment.getPhone(), phone)) {
                            if (TextUtils.equals(is_bind_wechat, "1")) {
                                showWechatIsRegisterDialog();
                            } else if (TextUtils.equals(is_reg, "1")) {
                                phoneFragment.setRegisterPhone(phone);
                                showIsRegisterHintDialog(phone, countryId, countryCode);
                            }
                        }


                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                    }
                }).start(new DefaultResponse());
    }


    private String phone, inviteCode, countryId, countryCode;

    public void enter(String phone, String inviteCode, String countryId, String countryCode) {
        this.phone = phone;
        this.inviteCode = inviteCode;
        this.countryId = countryId;
        this.countryCode = countryCode;
        getCode(phone, 0, countryId, countryCode);
    }

    public void enter(String code) {
        showLoadingDialog();
        if (type == 1 || type == 2) {
            new HttpRequest<LoginResponse>()
                    .with(this)
                    .setApiCode(type == 1 ? ApiCst.login : ApiCst.register)
                    .addParam("mobile", phone)
                    .addParam("country_id", countryId)
                    .addParam("captcha", code)
                    .addParam("invite_code", inviteCode)
                    .setListener(new HttpRequest.OnNetworkListener<LoginResponse>() {
                        @Override
                        public void onSuccess(LoginResponse baseResponse) {
                            dissmissLoadingDialog();
                            UserInfoModel userInfoModel = baseResponse.userInfoModel;
                            if (userInfoModel.getStatus() == 99) {
                                BroadcastManagerUtil.getInstance(mContext).sendBroadcast(SealConst.BAN);
                                finish();
                                return;
                            }

                            SharedPreferencesUtils.setUser(mContext, userInfoModel);
                            new JPushManager().setAlias(String.valueOf(userInfoModel.getUser_id()));
                            finish();
                        }

                        @Override
                        public void onFail(String message, LoginResponse response) {
                            toast(message);
                            dissmissLoadingDialog();
                        }
                    }).start(new LoginResponse());
        } else {
            new HttpRequest<DefaultResponse>()
                    .with(this)
                    .setApiCode(ApiCst.bindmobile)
                    .addParam("mobile", phone)
                    .addParam("country_id", countryId)
                    .addParam("captcha", code)
                    .addParam("invite_code", inviteCode)
                    .addParam("openid", openid)
                    .addParam("avatar", icon)
                    .addParam("nickname", name)
                    .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                        @Override
                        public void onSuccess(DefaultResponse baseResponse) {
                            wxlogin();
                        }

                        @Override
                        public void onFail(String message, DefaultResponse response) {
                            toast(message);
                            dissmissLoadingDialog();
                        }
                    }).start(new DefaultResponse());
        }
    }


    private void wxlogin() {
        new HttpRequest<LoginResponse>()
                .with(this)
                .setApiCode(ApiCst.wxlogin)
                .addParam("openid", openid)
                .setListener(new HttpRequest.OnNetworkListener<LoginResponse>() {
                    @Override
                    public void onSuccess(LoginResponse baseResponse) {
                        dissmissLoadingDialog();
                        UserInfoModel userInfoModel = baseResponse.userInfoModel;
                        if (userInfoModel.getStatus() == 99) {
                            BroadcastManagerUtil.getInstance(mContext).sendBroadcast(SealConst.BAN);
                            return;
                        }
                        SharedPreferencesUtils.setUser(mContext, userInfoModel);
                        new JPushManager().setAlias(String.valueOf(userInfoModel.getUser_id()));
                        finish();
                    }

                    @Override
                    public void onFail(String message, LoginResponse response) {
                        toast(message);
                        dissmissLoadingDialog();
                    }
                }).start(new LoginResponse());
    }

    @Override
    public void onBackPressed() {
        if (viewPager.getCurrentItem() == 1) {
            viewPager.setCurrentItem(0);
        } else super.onBackPressed();
    }


    public void getCodeAgain() {
        getCode(phone, 0, countryId, countryCode);
    }

    @SuppressWarnings("unchecked")
    private void getCode(String mobile, int is_reg, String countryId, final String countryCode) {
        showLoadingDialog();
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode(ApiCst.sendCode)
                .addParam("invite_code", inviteCode)
                .addParam("is_new", 1)
                .addParam("country_id", countryId)
                .addParam("is_reg", is_reg == 0 ? null : is_reg)
                .addParam("mobile", mobile)
                .addParam("event", type == 1 ? "mobilelogin" : (type == 2 ? "register" : "bindmobile"))
                .setListener(new HttpRequest.OnNetworkListener() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        toast(response.message);
                        isRun = true;
                        new Thread(runnable).start();
                        codeFragment.setPhone((TextUtils.isEmpty(countryCode) ? "+86" : ("+" + countryCode)) + phone);
                        viewPager.setCurrentItem(1);
                        dissmissLoadingDialog();
                    }

                    @Override
                    public void onFail(String message, BaseResponse response) {
                        dissmissLoadingDialog();
                        if (response.returnNo == 111) {
                            showHintDialog();
                            return;
                        }
                        if (response.returnNo == 112) {
                            showRegisterHintDialog();
                            return;
                        }
                        toast(message);

                    }
                }).start(new DefaultResponse());

    }


    private void showIsRegisterHintDialog(final String mobile, final String countryId, final String countryCode) {
        new CommonDialog.Builder(mContext)
                .setMessage("该手机号已经注册，无需再次填写邀请码，可以快速绑定？")
                .setNegativeButton("暂不绑定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                })
                .setPositiveButton("快速绑定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        RegisterActivity.this.phone = mobile;
                        RegisterActivity.this.countryId = countryId;
                        RegisterActivity.this.countryCode = countryCode;
                        getCode(mobile, 1, countryId, countryCode);
                    }
                }).setCancelable(false).show();
    }


    private void showHintDialog() {
        new CommonDialog.Builder(mContext)
                .setMessage("该手机号已经被注册，请直接登录")
                .setNegativeButton("暂不", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("去登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).show();
    }

    private void showRegisterHintDialog() {
        new CommonDialog.Builder(mContext)
                .setMessage("当前手机号暂未注册，是否立即注册？")
                .setNegativeButton("暂不", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("去注册", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        RegisterActivity.startActivity(mContext, 2);
                    }
                }).show();
    }

    private void showWechatIsRegisterDialog() {
        new CommonDialog.Builder(mContext)
                .setMessage("该手机号已经绑定微信号，请更换其他号码绑定")
                .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }


    private boolean isRun = false;

    //验证码发送倒计时
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    phoneFragment.setEnabled(false);
                    codeFragment.setEnabled(false);
                }
            });
            for (int i = 60; i > 0; i--) {
                final int finalI = i;
                if (!isRun) return;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        phoneFragment.setTime(finalI);
                        codeFragment.setTime(finalI);
                    }
                });
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (!isRun) return;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    phoneFragment.setEnabled(true);
                    phoneFragment.setTime(0);
                    codeFragment.setEnabled(true);
                    codeFragment.setTime(0);
                }
            });
            isRun = false;
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        isRun = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (App.isLogin()) finish();
    }
}
